<template>
  <div class="home-content">
    <!-- 轮播图 -->
    <section class="banner-section">
      <el-carousel height="400px">
        <el-carousel-item v-for="item in banners" :key="item.id">
          <div class="banner-item" :style="{ backgroundImage: `url(${item.imageUrl})` }">
            <div class="banner-content">
              <h2>{{ item.title }}</h2>
              <p>{{ item.description }}</p>
              <el-button type="primary">立即查看</el-button>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </section>
    
    
    <!-- 热门推荐 -->
    <section class="section-block recommended">
      <div class="section-header">
        <h2>热门推荐</h2>
        <el-button type="text" @click="$router.push('/user/products?sort=sales')">查看更多 <i class="el-icon-arrow-right"></i></el-button>
      </div>
      
      <div class="product-grid">
        <div class="product-card" v-for="product in recommendedProducts" :key="product.id" @click="viewProductDetail(product.id)">
          <div class="product-image">
            <img :src="product.imageUrl" :alt="product.name" />
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <p class="product-desc">{{ product.description }}</p>
            <div class="product-price">¥{{ product.price }}</div>
<!--            <div class="product-rating">-->
<!--              <i class="el-icon-star-on" v-for="n in 5" :key="n"></i>-->
<!--              <span>({{ product.reviewCount }})</span>-->
<!--            </div>-->
          </div>
          <div class="product-actions">
            <el-button type="primary" size="small" @click.stop="addToCart(product)">加入购物车</el-button>
            <el-button type="text" size="small" icon="el-icon-star-off" @click.stop="addToFavorite(product)"></el-button>
          </div>
        </div>
      </div>
    </section>
    
    <!-- 新品上架 -->
    <section class="section-block new-arrivals">
      <div class="section-header">
        <h2>新品上架</h2>
        <el-button type="text" @click="$router.push('/user/products?sort=new')">查看更多 <i class="el-icon-arrow-right"></i></el-button>
      </div>
      
      <div class="product-grid">
        <div v-if="isLoading" class="loading-container">
          <div v-for="i in 4" :key="i" class="loading-card">
            <el-skeleton-item variant="image" style="width: 100%; height: 200px;" />
            <el-skeleton-item variant="p" style="width: 60%" />
            <el-skeleton-item variant="text" style="width: 100%" />
          </div>
        </div>
        <template v-else>
          <div class="product-card" v-for="product in newProducts" :key="product.id" @click="viewProductDetail(product.id)">
            <div class="product-image">
              <img :src="product.coverImage || (product.images && product.images.length > 0 ? product.images[0].imageUrl : 'https://via.placeholder.com/250x250?text=No+Image')" :alt="product.name" />
              <div class="new-badge">新品</div>
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-desc">{{ product.description || '暂无描述' }}</p>
              <div class="product-price">¥{{ product.price }}</div>
            </div>
            <div class="product-actions">
              <el-button type="primary" size="small" @click.stop="addToCart(product)">加入购物车</el-button>
              <el-button type="text" size="small" icon="el-icon-star-off" @click.stop="addToFavorite(product)"></el-button>
            </div>
          </div>
        </template>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import productApi, { IProductDto } from '../../api/product';

const router = useRouter();
const isLoading = ref(false);
const allProducts = ref<IProductDto[]>([]);

// 新品数据
const newProducts = ref<IProductDto[]>([]);

// 默认新品数据
const defaultNewProducts = [
  {
    id: '5',
    name: '多效修护眼霜',
    description: '淡化细纹，提亮眼周',
    price: 239.00,
    sku: 'SKU001',
    categoryId: 1,
    coverImage: 'https://via.placeholder.com/250x250?text=Eye+Cream'
  },
  {
    id: '6',
    name: '保湿润唇膏',
    description: '滋润保湿，修护唇部',
    price: 89.00,
    sku: 'SKU002',
    categoryId: 1,
    coverImage: 'https://via.placeholder.com/250x250?text=Lip+Balm'
  },
  {
    id: '7',
    name: '净颜洁面乳',
    description: '温和清洁，不紧绷',
    price: 129.00,
    sku: 'SKU003',
    categoryId: 1,
    coverImage: 'https://via.placeholder.com/250x250?text=Cleanser'
  },
  {
    id: '8',
    name: '轻盈散粉',
    description: '控油持妆，自然雾面',
    price: 179.00,
    sku: 'SKU004',
    categoryId: 1,
    coverImage: 'https://via.placeholder.com/250x250?text=Powder'
  }
];

// 热门推荐商品数据 - 从所有商品中随机选择4个
const recommendedProducts = computed(() => {
  if (allProducts.value.length === 0) {
    // 如果全部商品还没有加载，返回默认值
    return [
      {
        id: 8,
        name: '轻盈散粉',
        description: '控油持妆，自然雾面',
        price: 179.00,
        reviewCount: 195,
        imageUrl: 'https://via.placeholder.com/250x250?text=Powder'
      },
      {
        id: 11,
        name: '玫瑰香水',
        description: '优雅迷人，持久留香',
        price: 259.00,
        reviewCount: 137,
        imageUrl: 'https://via.placeholder.com/250x250?text=Perfume'
      },
      {
        id: 3,
        name: '丝绒哑光口红',
        description: '持久显色，不易脱妆',
        price: 159.00,
        reviewCount: 246,
        imageUrl: 'https://via.placeholder.com/250x250?text=Lipstick'
      },
      {
        id: 12,
        name: '矿物眼影盘',
        description: '多色搭配，打造精致眼妆',
        price: 149.00,
        reviewCount: 118,
        imageUrl: 'https://via.placeholder.com/250x250?text=Eyeshadow'
      }
    ];
  }
  
  // 打乱全部商品数组并选取前4个
  return shuffleArray([...allProducts.value])
    .slice(0, 4)
    .map(product => ({
      id: product.id,
      name: product.name,
      description: product.description || '精选美妆产品',
      price: product.price,
      reviewCount: Math.floor(Math.random() * 200) + 50, // 随机生成评价数
      imageUrl: product.coverImage || 'https://via.placeholder.com/250x250?text=Beauty'
    }));
});

// 打乱数组的辅助函数
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

// 限时特惠
const flashSaleProducts = ref([
  {
    id: 9,
    name: '水光精华面膜',
    salePrice: 99.00,
    originalPrice: 199.00,
    discount: '5折',
    imageUrl: 'https://via.placeholder.com/200x200?text=Mask'
  },
  {
    id: 10,
    name: '清透防晒霜',
    salePrice: 129.00,
    originalPrice: 229.00,
    discount: '5.6折',
    imageUrl: 'https://via.placeholder.com/200x200?text=Sunscreen'
  },
  {
    id: 11,
    name: '玫瑰香水',
    salePrice: 259.00,
    originalPrice: 459.00,
    discount: '5.6折',
    imageUrl: 'https://via.placeholder.com/200x200?text=Perfume'
  },
  {
    id: 12,
    name: '矿物眼影盘',
    salePrice: 149.00,
    originalPrice: 299.00,
    discount: '5折',
    imageUrl: 'https://via.placeholder.com/200x200?text=Eyeshadow'
  },
  {
    id: 13,
    name: '纤长睫毛膏',
    salePrice: 99.00,
    originalPrice: 199.00,
    discount: '5折',
    imageUrl: 'https://via.placeholder.com/200x200?text=Mascara'
  }
]);

// 轮播图数据
const banners = ref([
  {
    id: 1,
    title: '夏季新品，清透水润',
    description: '限时优惠，满300减50',
    imageUrl: '/src/assets/首页1.jpg'
  },
  {
    id: 2,
    title: '明星产品，口碑之选',
    description: '大牌联合，折扣享不停',
    imageUrl: '/src/assets/首页2.jpg'
  },
  {
    id: 3,
    title: '会员专享，独家优惠',
    description: '新人首单，额外95折',
    imageUrl: '/src/assets/首页3.jpg'
  }
]);

// 获取全部商品数据
const fetchAllProducts = async () => {
  try {
    console.log('获取全部商品数据');
    const result = await productApi.getProductsPage({
      page: 0,
      size: 20, // 获取前20个商品，足够随机选择了
      sort: 'id',
      direction: 'desc'
    });
    
    console.log('API返回的全部商品数据:', result);
    
    if (result && result.data && result.data.content) {
      allProducts.value = result.data.content;
      console.log('获取到的商品数量:', allProducts.value.length);
    } else {
      console.warn('未获取到商品数据');
    }
  } catch (error) {
    console.error('获取商品失败:', error);
    ElMessage.error('获取商品数据失败');
  }
};

// 获取新品数据
const fetchNewProducts = async () => {
  isLoading.value = true;
  try {
    console.log('获取新品商品数据');
    const result = await productApi.getNewProducts(4); // 获取4个新品
    
    console.log('API返回的新品数据:', result);
    
    if (result && result.data && result.data.length > 0) {
      newProducts.value = result.data;
      console.log('获取到的新品数量:', newProducts.value.length);
    } else {
      console.warn('未获取到新品数据，使用默认数据');
      newProducts.value = defaultNewProducts;
    }
  } catch (error) {
    console.error('获取新品失败:', error);
    ElMessage.error('获取新品数据失败，使用默认数据');
    newProducts.value = defaultNewProducts;
  } finally {
    isLoading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchAllProducts(); // 先获取所有商品
  fetchNewProducts();
});

// 查看商品详情
const viewProductDetail = (productId) => {
  router.push(`/user/product/${productId}`);
};

// 添加到购物车
const addToCart = (product) => {
  // 这里应该调用添加到购物车的API
  ElMessage.success(`已将 ${product.name} 添加到购物车`);
  // 阻止事件冒泡
  event.stopPropagation();
};

// 添加到收藏
const addToFavorite = (product) => {
  // 这里应该调用添加到收藏的API
  ElMessage.success(`已将 ${product.name} 添加到收藏`);
  // 阻止事件冒泡
  event.stopPropagation();
};
</script>

<style scoped>
.home-content {
  width: 100%;
  overflow-x: hidden;
}

/* 轮播图 - 全宽设计 */
.banner-section {
  width: 100%;
  margin-bottom: 40px;
  overflow: hidden;
}

.banner-section :deep(.el-carousel) {
  height: 60vh;
  min-height: 450px;
  max-height: 600px;
}

.banner-section :deep(.el-carousel__container) {
  height: 100%;
}

.banner-item {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  background-size: cover;
  background-position: center;
  position: relative;
}

.banner-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0.2) 50%, rgba(0,0,0,0) 100%);
}

.banner-content {
  position: relative;
  max-width: 600px;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  padding-left: 5%;
  z-index: 1;
}

.banner-content h2 {
  font-size: 48px;
  margin-bottom: 20px;
  font-weight: 700;
  line-height: 1.2;
}

.banner-content p {
  font-size: 20px;
  margin-bottom: 30px;
  line-height: 1.6;
}

.banner-content .el-button {
  padding: 12px 30px;
  font-size: 18px;
  border-radius: 4px;
}

/* 商品区块 - 全宽设计 */
.section-block {
  background-color: #fff;
  padding: 40px 5%;
  margin-bottom: 40px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  width: 100%;
}

.flash-sale {
  background-color: #FFF8F9;
}

.new-arrivals {
  background-color: #F8F9FD;
}

.recommended {
  background-color: #FAFAFA;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 32px;
  color: #303133;
  font-weight: bold;
  position: relative;
}

.section-header h2:after {
  content: '';
  position: absolute;
  bottom: -21px;
  left: 0;
  width: 50px;
  height: 3px;
  background-color: #FF6B98;
}

.countdown {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 18px;
}

.time-box {
  background-color: #303133;
  color: #fff;
  padding: 6px 10px;
  border-radius: 4px;
  margin: 0 5px;
  font-weight: bold;
  font-size: 22px;
}

/* 商品列表 - 全宽设计 */
.product-scroll {
  overflow-x: auto;
  padding: 0;
  margin: 0;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.product-scroll::-webkit-scrollbar {
  display: none;
}

.product-list {
  display: flex;
  gap: 25px;
  padding-bottom: 15px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30px;
}

.product-card {
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s;
  position: relative;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
}

.flash-product {
  min-width: 280px;
}

.product-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
}

.product-image {
  position: relative;
  overflow: hidden;
  height: 280px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.5s;
}

.product-card:hover .product-image img {
  transform: scale(1.1);
}

.discount-badge, .new-badge {
  position: absolute;
  top: 15px;
  right: 15px;
  background-color: #FF6B98;
  color: white;
  padding: 5px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: bold;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
}

.new-badge {
  background-color: #67C23A;
}

.product-info {
  padding: 25px;
}

.product-name {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-desc {
  color: #606266;
  font-size: 15px;
  margin: 0 0 15px 0;
  height: 48px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.6;
}

.product-price {
  color: #FF6B98;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 15px;
}

.current-price {
  color: #FF6B98;
  font-size: 24px;
  font-weight: bold;
}

.original-price {
  color: #909399;
  font-size: 16px;
  text-decoration: line-through;
  margin-left: 10px;
}

.product-rating {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.product-rating i {
  color: #FFCC00;
  font-size: 16px;
  margin-right: 1px;
}

.product-rating span {
  color: #909399;
  font-size: 14px;
  margin-left: 8px;
}

.product-actions {
  display: flex;
  justify-content: space-between;
  padding: 0 25px 25px;
}

.product-actions .el-button {
  font-weight: bold;
  height: 40px;
}

.buy-button {
  width: 100%;
  margin-top: 15px;
  height: 45px;
  font-weight: bold;
  font-size: 16px;
  letter-spacing: 1px;
}

/* 响应式布局 - 注重桌面体验 */
@media (max-width: 1400px) {
  .product-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 25px;
  }
  
  .product-image {
    height: 240px;
  }
  
  .banner-content h2 {
    font-size: 42px;
  }
}

@media (max-width: 1200px) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 25px;
  }
  
  .banner-section :deep(.el-carousel) {
    height: 55vh;
  }
  
  .banner-content h2 {
    font-size: 38px;
  }
  
  .entry-icon {
    width: 60px;
    height: 60px;
  }
  
  .entry-icon i {
    font-size: 28px;
  }
}

@media (max-width: 992px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
  
  .product-image {
    height: 220px;
  }
  
  .banner-section :deep(.el-carousel) {
    height: 50vh;
  }
  
  .banner-content h2 {
    font-size: 32px;
  }
  
  .banner-content p {
    font-size: 18px;
  }
  
  .section-header h2 {
    font-size: 28px;
  }
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .product-image {
    height: 180px;
  }
  
  .product-info {
    padding: 15px;
  }
  
  .banner-section :deep(.el-carousel) {
    height: 40vh;
  }
  
  .banner-content h2 {
    font-size: 28px;
  }
  
  .banner-content p {
    font-size: 16px;
  }
  
  .quick-entry {
    flex-wrap: wrap;
  }
  
  .entry-item {
    width: 30%;
    margin-bottom: 15px;
  }
  
  .section-block {
    padding: 30px 5%;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .countdown {
    margin: 15px 0;
  }
}

/* 添加加载容器样式 */
.loading-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30px;
  width: 100%;
}

.loading-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

@media (max-width: 1200px) {
  .loading-container {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .loading-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .loading-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
}
</style> 